const { Model, Schema } = require('../helps/model');
const { formatData } = require('../helps/tools');
const uuidv4 = require('uuid/v4');

// const { executor } = require('../helps/model');
// CREATE TABLE `robot` (
//   `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
//   `code` varchar(255)  NOT NULL COMMENT '机器人标识',
//   `avatar` varchar(255) NOT NULL DEFAULT "" COMMENT '头像',
//   `nickname` varchar(255)  NOT NULL DEFAULT "" COMMENT '昵称',
//   `birthday` varchar(255) NOT NULL DEFAULT "" COMMENT '生日',
//   `gender` tinyint(1) unsigned NOT NULL DEFAULT 0 COMMENT '性别：1男，2女',
//   `version` varchar(255) NOT NULL DEFAULT "" COMMENT '当前版本',
//   `alive_time` datetime COMMENT '最后激活时间',
//   `token` varchar(255) NOT NULL DEFAULT "" COMMENT '登录token',
//   `refresh_token` varchar(255) NOT NULL DEFAULT "" COMMENT '刷新token',
//   `expire_time` datetime COMMENT '最后有效时间',
//   `mqtt_username` varchar(255) NOT NULL DEFAULT "" COMMENT 'mqtt账号密码',
//   `mqtt_password` varchar(255) NOT NULL DEFAULT "" COMMENT 'mqtt密码',
//   `night_status` tinyint(1) unsigned NOT NULL DEFAULT 0 COMMENT '夜间模式开关：0关，1开',
//   `night_start_time` datetime COMMENT '夜间模式开启时间',
//   `night_end_time` datetime COMMENT '夜间模式结束时间',
//   `anti_addiction_status` tinyint(1) unsigned NOT NULL DEFAULT 0 COMMENT '防沉迷模式开关：0关，1开',
//   `anti_addiction_duration` int(11) unsigned NOT NULL DEFAULT 0 COMMENT '防沉迷持续时间:分钟',
//   `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
//   `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
//   `delete_time` datetime,
//   PRIMARY KEY (`id`),
//   KEY `token` (`token`) USING BTREE,
//   KEY `refresh_token` (`refresh_token`) USING BTREE
// ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='机器人表';
const schema = new Schema({
  primary: 'id',
  create_time: true,
  update_time: true,
  soft_delete: true,
  auto_increment: true,
  fields: ['id', 'code', 'avatar', 'nickname', 'birthday', 'gender', 'version', 'alive_time', 'token', 'refresh_token', 'expire_time', 'mqtt_username', 'mqtt_password', 'night_status', 'night_start_time', 'night_end_time', 'anti_addiction_status', 'anti_addiction_duration'],
  default: {
    avatar: '',
    nickname: '',
    birthday: '',
    gender: 0,
    version: '',
    token: '',
    refresh_token: '',
    mqtt_username: '',
    mqtt_password: '',
    night_status: 0,
    anti_addiction_status: 0,
    anti_addiction_duration: 0,
  },
});

/**
 * 刷新token，更改refreshToken
 */
schema.methods.refreshToken = function (seconds) {
  this.token = uuidv4();
  this.refresh_token = uuidv4();
  let now = new Date();
  now.setSeconds(now.getSeconds() + seconds);
  this.expire_time = now;
  return this.save();
};

/**
 * 保存最后登入时间
 */
schema.methods.aliveSave = function () {
  this.alive_time = new Date();
  return this.save();
};

/**
 * @param data { mqtt_username, mqtt_password }
 * @param {*} record
 */
schema.methods.bindMqtt = function ({ mqtt_username, mqtt_password }) {
  this.mqtt_username = mqtt_username;
  this.mqtt_password = mqtt_password;
  return this.save();
};

/**
 * 获取机器人信息
 */
schema.methods.info = function () {
  return {
    code: this.code,
    status: this.status,
    alive_time: this.alive_time,
    version: this.version,
    avatar: this.avatar,
    nickname: this.nickname,
    birthday: this.birthday,
    gender: this.gender,
  };
};

/**
 * 修改用户信息
 * @param {*}
 */
schema.methods.put = function ({ avatar, nickname, birthday, gender, night_status, night_start_time, night_end_time, anti_addiction_status, anti_addiction_duration }) {
  if (avatar) this.avatar = avatar;
  if (nickname) this.nickname = nickname;
  if (birthday) this.birthday = birthday;
  if (gender) this.gender = gender;
  if (night_status) this.night_status = night_status;
  if (night_start_time) this.night_start_time = night_start_time;
  if (night_end_time) this.night_end_time = night_end_time;
  if (anti_addiction_status) this.anti_addiction_status = anti_addiction_status;
  if (anti_addiction_duration) this.anti_addiction_duration = anti_addiction_duration;

  return this.save();
};

export const model = new Model('robot', schema);

/**
 * 查找
 * @param id
 * @returns {*}
 */
export function get(id) {
  return model.findByKey(id);
}

/**
 * 查找列表
 * @param ids
 * @returns {*}
 */
export function getIds(ids) {
  return model.findByQuery({
    where: [
      ['id', 'in', ids],
    ],
  });
}

/**
 * 创建
 * @param dataList
 * @returns {*}
 */
export function add(dataList) {
  return model.insertBatch(dataList);
}

/**
 * 更新
 * @param id
 * @param data
 * @returns {*}
 */
export function put(id, data) {
  return model.updateByKey(id, formatData(schema.baseFields(), data));
}

/**
 * 删除
 * @param id
 * @returns {*}
 */
export function del(id) {
  return model.deleteByKey(id);
}

/**
 * 列表分页
 * @param page
 * @param number
 * @returns {*}
 */
export function search(where, page = 1, number = 50, order = 'id', direction = 'desc') {
  return model.findListAndCount(where, page, number, `\`${order}\` ${direction}`);
}

export function list(page, number, order, direction) {
  return search([], page, number, order, direction);
}

/**
 * 根据机器码获取机器人
 * @param {*} code
 */
export function getByCode(code) {
  return model.one({
    where: [
      ['code', '=', code],
    ],
  });
}

/**
 * 根据token获取机器人
 * @param {*} code
 */
export function getByToken(token) {
  return model.one({
    where: [
      ['token', '=', token],
    ],
  });
}
